from collections import defaultdict
from itertools import chain

import pymongo
import time
import json
import requests
import redis
from wxpy import Bot, Group, TEXT, Tuling
from datetime import date, timedelta
# 127
client_127 = pymongo.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
db_127 = client_127.cs_recharge
coll_127 = db_127.rechange
conn = redis.Redis()
# 1688
client_1688 = pymongo.MongoClient(username='user', password='cmcc5188')
db_1688 = client_1688.recharge
coll_1688 = db_1688.rechange
bot = Bot(console_qr=2, cache_path="botoo.pkl")
groups = bot.groups()
group = None
for i in groups:
    if i.name == '127星恒太':
        group = i
if not group:
    print("找不到群")

prov_name = {'100': '北京',
             '200': '广东',
             '210': '上海',
             '220': '天津',
             '240': '辽宁',
             '250': '江苏',
             '270': '湖北',
             '280': '四川',
             '230': '重庆',
             '290': '陕西',
             '311': '河北',
             '351': '山西',
             '371': '河南',
             '431': '吉林',
             '451': '黑龙江',
             '471': '内蒙',
             '472': '内蒙古',
             '531': '山东',
             '551': '安徽',
             '571': '浙江',
             '591': '福建',
             '731': '湖南',
             '771': '广西',
             '791': '江西',
             '851': '贵州',
             '871': '云南',
             '891': '西藏',
             '898': '海南',
             '931': '甘肃',
             '951': '宁夏',
             '971': '青海',
             '991': '新疆'}

tuling = Tuling(api_key='b5cfe52d4b3942ca93aac8b8013dd835')

help_message = """
H：帮助
L：查询当前未知省份。
C省份：C广东。关闭广东。
O省份：O广东。开启广东。
CL：查看关闭省份列表。
UL：联通未知省份。
UO数量：打开并设置关闭数量。UO160
UC：UC广东。联通关闭广东。
UP：U广东。联通开启广东。
UN：联通查看关闭省份列表。
"""
own_proxy = ['',
             'http://cmcc:epay1688@172.18.232.56:8120',
             'http://cmcc:epay1688@172.18.232.47:8120',
             'http://cmcc:epay1688@172.18.232.48:8120',
             'http://cmcc:epay1688@172.18.232.51:8120',
             'http://cmcc:epay1688@172.18.232.45:8120',
             'http://cmcc:epay1688@172.18.232.49:8120',
             'http://cmcc:epay1688@172.18.232.57:8120',
             'http://cmcc:epay1688@172.18.232.46:8120',
             'http://cmcc:epay1688@172.18.232.53:8120',
             'http://cmcc:epay1688@172.18.232.61:8120',
             'http://cmcc:epay1688@172.18.232.58:8120',
             'http://cmcc:epay1688@172.18.232.52:8120',
             'http://cmcc:epay1688@172.18.232.54:8120',
             'http://cmcc:epay1688@172.18.232.62:8120',
             'http://cmcc:epay1688@172.18.232.60:8120',
             'http://cmcc:epay1688@172.18.232.50:8120',
             'http://cmcc:epay1688@172.18.232.44:8120',
             'http://cmcc:epay1688@172.18.232.59:8120',
             'http://cmcc:epay1688@172.18.232.55:8120',
             'http://cmcc:epay1688@172.18.140.229:8120']

def add_porxy(orderid):
    for i in own_proxy:
        conn.sadd('un_proxy', i)

@bot.register(Group, TEXT)
def auto_reply(msg):
    print(msg.text)
    if isinstance(msg.chat, Group) and not msg.is_at:
        print("-----")
        return
    else:

        text = msg.text.replace('\u2005', ' ')
        text = text.split(" ")[1]
        print(text)
        # 回复消息内容和类型
        if text == "L":
            # res = conn.hgetall('cmcc10085_unknow')
            # res = {k.decode(): v.decode() for k, v in res.items()}
            # message = "; ".join(["%s:%s" % (k, v) for k, v in res.items()])
            # print("查询省份")
            # msg.reply("85移动各省未知数量：" + message)
            res = conn.hgetall('cmcc_amount')
            res = {k.decode(): v.decode() for k, v in res.items()}
            message = "; ".join(["%s:%s" % (k, v) for k, v in res.items()])
            msg.reply("86移动：" + message)

        elif text == "H":

            msg.reply(help_message)
        elif text == "CL":
            message = conn.smembers('unused_85_prov')
            msg.reply(";".join(i.decode() for i in message))
            message = conn.smembers('unused_86_prov')
            msg.reply(";".join(i.decode() for i in message))
        elif text.startswith("C"):
            prov = text.strip("C")
            if prov not in prov_name.values():
                msg.reply("省份名称错误")
            else:
                conn.sadd("unused_86_prov", prov)
                msg.reply("关闭%s成功" % prov)
        elif text.startswith("O"):
            prov = text.strip("O")
            if prov not in prov_name.values():
                msg.reply("省份名称错误")
            else:
                conn.srem("unused_86_prov", prov)
                msg.reply("开启%s成功" % prov)
        elif text == "UL":
            res = conn.hgetall('unicom_unkonw')
            res = {k.decode(): v.decode() for k, v in res.items()}
            message = "; ".join(["%s:%s" % (k, v) for k, v in sorted(res.items(), key=lambda k:float(k[1]))])
            msg.reply("联通各省未知数量：" + message + "\n")
        elif text.startswith("UO"):
            num = text.strip("UO")
            conn.set("is_unicom_close", 0)
            conn.set("close_unicom_no", num)
            msg.reply("设置成功")
        elif text.startswith("UC"):
            prov = text.strip("UC")
            if prov not in prov_name.values():
                msg.reply("省份名称错误")
            else:
                conn.sadd("unused_un_prov", prov)
                msg.reply("关闭%s成功" % prov)
        elif text.startswith("UP"):
            prov = text.strip("UP")
            if prov not in prov_name.values():
                msg.reply("省份名称错误")
            else:
                conn.srem("unused_un_prov", prov)
                msg.reply("开启%s成功" % prov)
        elif text == "UN":
            message = conn.smembers('unused_un_prov')
            return ";".join(i.decode() for i in message)
        # elif text == 'AP':
        #     add_porxy('974762719965149')
        #     return "添加代理成功"
        elif text == 'PN':
            num = conn.scard("un_proxy")
            return "当前代理数量%d" % num
        elif text == 'AL':
            if msg.sender.name in ('100', '127星恒太', 'core'):
                un_amount = conn.hget('unicom_unkonw', '成功金额')
                cm_amount = conn.hget('cmcc_amount', '成功金额')
                ct_amount = conn.hget('ctcc_amount', '成功金额')
                un_amount = int(un_amount.decode())
                cm_amount = int(cm_amount.decode())
                ct_amount = int(ct_amount.decode())
                return "移动：%d， 联通：%d, 电信：%d 总额：%d" % (cm_amount, un_amount, ct_amount, ct_amount+un_amount+cm_amount)
            else:
                msg.reply_image("image/timg.gif")
# else:
        #     tuling.do_reply(msg)

bot.join()

